/**
 * 用户管理模块
 */
var person = {};
var tableRowLength = 0;
var params = [];
var admin = {};
/**
 * 用户查询条件集合
 */
var auditCondition = {
	 startDate : "",
	 userType : "",
	 userStatus : "",
	 endDate : "",
 	 pageNo : "",
 	 pageSize : "",
 	 industryId : '',
 	 locationId : ''
}


/**
 * 填充审核状态
 *//*
function setManageMentAuditStautsInfo() {
	var selectData = [];
	//填充下拉框
	$.getJSON('../data/managment/auditManagementStatus.json',function(data) {
		for(var i = 0; i<data.length;i++) {
			selectData.push({
				id : data[i].id,
				name : data[i].name
			});
		}
	})
	setTimeout(function() {
		getOption(selectData,'auditStatusContent');
	},200);
}*/

/**
 *填充用户默认信息
 * @param pageNo
 * @param pageSize
 * @param userType
 */
function getManageMentFiled(pageNo, pageSize,userType) {
	auditCondition.pageNo = pageNo;
	auditCondition.pageSize = pageSize;
	auditCondition.userType = userType;
//	console.log(auditCondition);
	/*switch(userType){
		case 1 : getPersonByCondition();break;
		case 2 : getCompanyByCondition();break;
		case 3 : getAgencyByCondition();break;
	}*/
	getSelectFunByCondition();
}

/**
 * 查询信息
 */
function findByCondition() {
	
	//var userType = auditCondition.userType;
	auditCondition.industryId = person.industryId === undefined ? '' : person.industryId;
	auditCondition.locationId = person.locationId === undefined ? '' : person.locationId;
	auditCondition.startDate = getTimeStamp($('#startDate').val()) || '';
	auditCondition.endDate = getTimeStamp($('#endDate').val()) || '';
	//console.log(auditCondition);
	getSelectFunByCondition();
}

/**
 *	选择指定的查询用户
 */
function getSelectFunByCondition() {
	switch(auditCondition.userType) {
		case 1 : getPersonByCondition();break;//个人会员
		case 2 : getCompanyByCondition();break;//企业
		case 3 : getAgencyByCondition();break;//中介
		case 4 : getCollegeByCondition(); break;//高校 
		case 5 : getScientifyByCondition();break;//科研
		case 6 : getAdminByCondition();break;//平台管理员
		case 7 : getSuperByCondition();break;//超级管理员
	}
}


/**
 * 用户类型改变
 */
function userTypeChange(){
	$('#userMangamentType').on('change', function() {
		var userType = parseInt(this.value);
		getManageMentFiled(1,5,userType);
	})
}


/**
 * 获取个人用户信息
 */
function getPersonByCondition() {
	$.ajax({
		url : '../userInfo/getPersonInfoPageByCondition',
		type : 'POST',
		dataType : 'json',
		contentType : 'application/json',
		data :  JSON.stringify(auditCondition),
		success : function (data) {
			console.log(data);
			if(data.success) {
				//console.log(data);
				//渲染
				tableRowLength = data.result.resultList.length;
				renderManagementUser(data.result.resultList, 'userListContent');
				//分页
				renderPage(tableRowLength, data.result.totalPage,auditCondition.pageNo,auditCondition.pageSize,getPersonByCondition,auditCondition,'userManagementPageContent');
			}
		}
	})
}




/**
 * 渲染用户信息管理表格信息
 * @param data
 * @param contentName
 */
function renderManagementUser(data,contentName) {
	$('#' + contentName).empty();
	for(var i = 0;i < data.length;i++) {
		$('#' + contentName).append(assableManageMentUser(i,data[i],contentName));
	}
}

/**
 *	拼装用户信息管理表格信息字符串
 * @param obj
 * @returns {String}
 */
function assableManageMentUser(index,obj,contentName) {
	return  '<tr><td>'+ obj.userId +'</td><td>'+ obj.userName +'</td><td>'+ getLocalTime(obj.registerTime) +
	'</td><td>'+ matchJsonFile('locationId', obj.locationId) +'</td><td>'+ toggleStauts(obj.userStatus, '可用', '禁用') +'</td><td><button type="button" name="'+ obj.userId +
	'" class="btn btn-info" onclick="getManagementUserDetails(this);" style="margin-right:10px;">详情</button><button type="button"  name="'+ obj.userId+
	'" style="margin-right:10px;" class="btn" onclick="updateManagementUserStatus(this,'+ index +', '+ contentName +');">切换状态</button><button type="button" name="'+ obj.userId+
	'" class="btn btn-danger" onclick="showDeleteModule(this);">删除</button></td></tr>';
}

/**
 * 查询企业信息
 */
function getCompanyByCondition(){
	$.ajax({
		url : '../userInfo/getCompanyInfoPageByCondition',
		type : 'POST',
		dataType : 'json',
		contentType : 'application/json',
		data :  JSON.stringify(auditCondition),
		success : function (data) {
			//console.log(data);
			if(data.success) {
				//console.log(data);
				//渲染
				tableRowLength = data.result.resultList.length;
				renderManagementCompany(data.result.resultList, 'userListContent');
				//分页
				renderPage(tableRowLength, data.result.totalPage,auditCondition.pageNo,auditCondition.pageSize,getCompanyByCondition,auditCondition,'userManagementPageContent');
			}
		}
	})
}



/**
 * 渲染用户信息管理表格信息
 * @param data
 * @param contentName
 */
function renderManagementCompany(data,contentName) {
	//console.log(data);
	$('#' + contentName).empty();
	for(var i = 0;i < data.length;i++) {
		$('#' + contentName).append(assableManagementCompany(i,data[i],contentName));
	}
}

/**
 *	拼装用户信息管理表格信息字符串
 * @param obj
 * @returns {String}
 */
function assableManagementCompany(index,obj,contentName) {
	return  '<tr><td>'+ obj.userId +'</td><td>'+ obj.userName +'</td><td>'+ getLocalTime(obj.registerTime) +
	'</td><td>'+ matchJsonFile('locationId', obj.locationId) +'</td><td>'+ toggleStauts(obj.userStatus, '可用', '禁用') +'</td><td><button type="button" name="'+ obj.userId +
	'" class="btn btn-info" onclick="getManagementCompanyDetails(this);" style="margin-right:10px;">详情</button><button type="button"  name="'+ obj.userId+
	'" style="margin-right:10px;" class="btn" onclick="updateManagementUserStatus(this,'+ index +', '+ contentName +');">切换状态</button><button type="button" name="'+ obj.userId+
	'" class="btn btn-danger" onclick="showDeleteModule(this);">删除</button></td></tr>';
}


/**
 * 查询中介机构用户信息
 */
function getAgencyByCondition() {
	$.ajax({
		url : '../userInfo/getAgencyInfoPageByCondition',
		type : 'POST',
		dataType : 'json',
		contentType : 'application/json',
		data :  JSON.stringify(auditCondition),
		success : function (data) {
			//console.log(data);
			if(data.success) {
				//console.log(data);
				//渲染
				tableRowLength = data.result.resultList.length;
				renderManagementAgency(data.result.resultList, 'userListContent');
				//分页
				renderPage(tableRowLength, data.result.totalPage,auditCondition.pageNo,auditCondition.pageSize,getAgencyByCondition,auditCondition,'userManagementPageContent');
			}
		}
	})
}

/**
 * 渲染中介机构用户信息管理表格信息
 * @param data
 * @param contentName
 */
function renderManagementAgency(data,contentName) {
	//console.log(data);
	$('#' + contentName).empty();
	for(var i = 0;i < data.length;i++) {
		$('#' + contentName).append(assableManagementAgency(i,data[i],contentName));
	}
}

/**
 *	拼装中介机构用户信息管理表格信息字符串
 * @param obj
 * @returns {String}
 */
function assableManagementAgency(index,obj,contentName) {
	return  '<tr><td>'+ obj.userId +'</td><td>'+ obj.userName +'</td><td>'+ getLocalTime(obj.registerTime) +
	'</td><td>'+ matchJsonFile('locationId', obj.locationId) +'</td><td>'+ toggleStauts(obj.userStatus, '可用', '禁用') +'</td><td><button type="button" name="'+ obj.userId +
	'" class="btn btn-info" onclick="getManagementAgencyDetails(this);" style="margin-right:10px;">详情</button><button type="button"  name="'+ obj.userId+
	'" style="margin-right:10px;" class="btn" onclick="updateManagementUserStatus(this,'+ index +', '+ contentName +');">切换状态</button><button type="button" name="'+ obj.userId+
	'" class="btn btn-danger" onclick="showDeleteModule(this);">删除</button></td></tr>';
}

/**
 * 查询高校用户信息
 */
function getCollegeByCondition() {
	$.ajax({
		url : '../userInfo/getColleageInfoPageByCondition',
		type : 'POST',
		dataType : 'json',
		contentType : 'application/json',
		data :  JSON.stringify(auditCondition),
		success : function (data) {
			//console.log(data);
			if(data.success) {
				//console.log(data);
				//渲染
				tableRowLength = data.result.resultList.length;
				renderManagementCollege(data.result.resultList, 'userListContent');
				//分页
				renderPage(tableRowLength, data.result.totalPage,auditCondition.pageNo,auditCondition.pageSize,getCollegeByCondition,auditCondition,'userManagementPageContent');
			}
		}
	})
}

/**
 * 渲染高校管理信息
 * @param data
 * @param contentName
 */
function renderManagementCollege(data,contentName) {
	//console.log(data);
	$('#' + contentName).empty();
	for(var i = 0;i < data.length;i++) {
		$('#' + contentName).append(assableManagementCollege(i,data[i],contentName));
	}
}

/**
 * 拼装高校信息字符串
 * @param index
 * @param obj
 * @param contentName
 * @returns {String}
 */
function assableManagementCollege(index,obj,contentName) {
	return  '<tr><td>'+ obj.userId +'</td><td>'+ obj.userName +'</td><td>'+ getLocalTime(obj.registerTime) +
	'</td><td>'+ matchJsonFile('locationId', obj.locationId) +'</td><td>'+ toggleStauts(obj.userStatus, '可用', '禁用') +'</td><td><button type="button" name="'+ obj.userId +
	'" class="btn btn-info" onclick="getManagementCollegeDetails(this);" style="margin-right:10px;">详情</button><button type="button"  name="'+ obj.userId+
	'" style="margin-right:10px;" class="btn" onclick="updateManagementUserStatus(this,'+ index +', '+ contentName +');">切换状态</button><button type="button" name="'+ obj.userId+
	'" class="btn btn-danger" onclick="showDeleteModule(this);">删除</button></td></tr>';
}

/**
 * 查询科研单位管理信息
 */
function getScientifyByCondition() {
	$.ajax({
		url : '../userInfo/getScientifyInfoPageByCondition',
		type : 'POST',
		dataType : 'json',
		contentType : 'application/json',
		data :  JSON.stringify(auditCondition),
		success : function (data) {
			//console.log(data);
			if(data.success) {
				//console.log(data);
				//渲染
				tableRowLength = data.result.resultList.length;
				renderManagementScientify(data.result.resultList, 'userListContent');
				//分页
				renderPage(tableRowLength, data.result.totalPage,auditCondition.pageNo,auditCondition.pageSize,getScientifyByCondition,auditCondition,'userManagementPageContent');
			}
		}
	})
}


/**
 * 渲染科研单位管理信息
 * @param data
 * @param contentName
 */
function renderManagementScientify(data,contentName) {
	//console.log(data);
	$('#' + contentName).empty();
	for(var i = 0;i < data.length;i++) {
		$('#' + contentName).append(assableManagementScientify(i,data[i],contentName));
	}
}

/**
 * 拼装科研单位信息字符串
 * @param index
 * @param obj
 * @param contentName
 * @returns {String}
 */
function assableManagementScientify(index,obj,contentName) {
	return  '<tr><td>'+ obj.userId +'</td><td>'+ obj.userName +'</td><td>'+ getLocalTime(obj.registerTime) +
	'</td><td>'+ matchJsonFile('locationId', obj.locationId) +'</td><td>'+ toggleStauts(obj.userStatus, '可用', '禁用') +'</td><td><button type="button" name="'+ obj.userId +
	'" class="btn btn-info" onclick="getManagementScientifyDetails(this);" style="margin-right:10px;">详情</button><button type="button"  name="'+ obj.userId+
	'" style="margin-right:10px;" class="btn" onclick="updateManagementUserStatus(this,'+ index +', '+ contentName +');">切换状态</button><button type="button" name="'+ obj.userId+
	'" class="btn btn-danger" onclick="showDeleteModule(this);">删除</button></td></tr>';
}

/**
 * 管理者切换用户状态
 * @param userId
 */
function updateManagementUserStatus(target,index,contentName) {
	$.ajax({
		url : '../user/updateUserStatusById',
		type : 'POST',
		dataType : 'json',
		contentType : 'application/json',
		data :  JSON.stringify({
			userId : target.name
		}),
		success : function (data) {
			if(data.success) {
				toastr.success(data.msg);
				//切换
				getSelectFunByCondition();
			}else{
				toastr.error(data.msg);
			}
		}
	})
}


/**
 * 打开删除用户模态框，并保存删除的用户id
 * @param target
 */
function showDeleteModule(target) {
	params = [target.name];
	
	showModal('../modalTemplates/removeUser.html');
}

/**
 * 按指定用户id删除用户
 */
function deleteManagementUser() {
	$.ajax({
		url : '../user/delete',
		type : 'DELETE',
		dataType : 'json',
		contentType : 'application/json',
		data :  JSON.stringify({
			userId :params[0]
		}),
		success : function (data) {
			if(data.success) {
				toastr.success(data.msg);
			}else{
				toastr.error(data.msg);
			}
			//按照当前查询信息更新表格
			getSelectFunByCondition();
			$("#modalModule").modal('hide');  
		}
	})
}

/**
 * 区分高校还是科研
 */
function getSelectCollegeOrScientify() {
	if(auditCondition.userType === 4) {
		//高校
		getCollegeManagment({
			name : "高校单位管理"
		})
	}else if(auditCondition.userType === 5) {
		//科研
		getScientifyManagment({
			name : "科研单位管理"
		})
	}
}



/**
 * 获取用户详细信息
 * @param userId
 */
function getManagementUserDetails(target) {
	$.ajax({
		url : '../userInfo/getPersonInfoForManager',
		type : 'POST',
		dataType : 'json',
		contentType : 'application/json',
		data :  JSON.stringify({
			userId : target.name
		}),
		success : function (data) {
			if(data.success) {
				person=data.result;
				getPersonMangement(person.personName);
				setTimeout(function() {
					renderAuditContent('personManagment');
				},150);
			}
		}
	})
}

/**
 * 获取企业详细信息
 * @param target
 */
function getManagementCompanyDetails(target) {
	$.ajax({
		url : '../userInfo/getCompanyInfoForManager',
		type : 'POST',
		dataType : 'json',
		contentType : 'application/json',
		data :  JSON.stringify({
			userId : target.name
		}),
		success : function (data) {
			if(data.success) {
				person=data.result;
				getCompanyMangement(person.unitName);
				setTimeout(function() {
					renderAuditContent('companyManagment');
				},150);
			}
		}
	})
}

/**
 * 获取中介机构详细信息
 * @param target
 */
function getManagementAgencyDetails(target) {
	$.ajax({
		url : '../userInfo/getAgencyInfoForManager',
		type : 'POST',
		dataType : 'json',
		contentType : 'application/json',
		data :  JSON.stringify({
			userId : target.name
		}),
		success : function (data) {
			//console.log(data);
			if(data.success) {
				person=data.result;
				getAgencyMangement(person.unitName);
				setTimeout(function() {
					renderAuditContent('agencyManagement');
				},150);
			}
		}
	})
}

/**
 * 获取高校详细信息
 * @param target
 */
function getManagementCollegeDetails(target) {
	$.ajax({
		url : '../userInfo/getCollegeInfoForManager',
		type : 'POST',
		dataType : 'json',
		contentType : 'application/json',
		data :  JSON.stringify({
			userId : target.name
		}),
		success : function (data) {
			//console.log(data);
			if(data.success) {
				person=data.result;
				getCollegeAndScientifyMangement(person.unitName,'高校单位管理');
				setTimeout(function() {
					renderAuditContent('collegeAndScientifyManagment');
				},150);
			}
		}
	})
}

/**
 * 获取科研单位详细信息
 * @param target
 */
function getManagementScientifyDetails(target) {
	$.ajax({
		url : '../userInfo/getScientifyInfoForManager',
		type : 'POST',
		dataType : 'json',
		contentType : 'application/json',
		data :  JSON.stringify({
			userId : target.name
		}),
		success : function (data) {
			//console.log(data);
			if(data.success) {
				person=data.result;
				getCollegeAndScientifyMangement(person.unitName,'科研单位管理');
				setTimeout(function() {
					renderAuditContent('collegeAndScientifyManagment');
				},150);
			}
		}
	})
}

/**
 * **********************************    平台管理员模块 start    ************************************
 */

/**
 * 获取平台管理员信息
 */
function getAdminByCondition() {
	$.ajax({
		url : '../userInfo/getPlatformInfoPageByCondition',
		type : 'POST',
		dataType : 'json',
		contentType : 'application/json',
		data :  JSON.stringify(auditCondition),
		success : function (data) {
			//console.log(data);
			if(data.success) {
				//console.log(data);
				//渲染
				tableRowLength = data.result.resultList.length;
				renderManagementAdmin(data.result.resultList, 'adminListContent');
				//分页
				renderPage(tableRowLength, data.result.totalPage,auditCondition.pageNo,auditCondition.pageSize,getAdminByCondition,auditCondition,'adminManagementPageContent');
			}
		}
	})
}

/**
 * 超级管理员
 */
function getSuperByCondition() {
	$.ajax({
		url : '../userInfo/getSuperInfoPageByCondition',
		type : 'POST',
		dataType : 'json',
		contentType : 'application/json',
		data :  JSON.stringify(auditCondition),
		success : function (data) {
			//console.log(data);
			if(data.success) {
				//console.log(data);
				//渲染
				tableRowLength = data.result.resultList.length;
				renderManagementAdmin(data.result.resultList, 'adminListContent');
				//分页
				renderPage(tableRowLength, data.result.totalPage,auditCondition.pageNo,auditCondition.pageSize,getSuperByCondition,auditCondition,'adminManagementPageContent');
			}
		}
	})
}


/**
 * 渲染管理员信息管理表格信息
 * @param data
 * @param contentName
 */
function renderManagementAdmin(data,contentName) {
	$('#' + contentName).empty();
	for(var i = 0;i < data.length;i++) {
		$('#' + contentName).append(assableManageMentAdmin(i,data[i],contentName));
	}
}

/**
 *	拼装管理员信息管理表格信息字符串
 * @param obj
 * @returns {String}
 */
function assableManageMentAdmin(index,obj,contentName) {
	return  '<tr><td>'+ obj.userId +'</td><td>'+ obj.userName +'</td><td>'+ getLocalTime(obj.registerTime) +
	'</td><td>'+ matchJsonFile('locationId', obj.locationId) +'</td><td>'+ toggleStauts(obj.userStatus, '可用', '禁用') +'</td><td><button type="button" name="'+ obj.userId +
	'" class="btn btn-info" onclick="getManagementAdminDetails(this);" style="margin-right:10px;">详情</button><button type="button"  name="'+ obj.userId+
	'" style="margin-right:10px;" class="btn" onclick="updateManagementUserStatus(this,'+ index +', '+ contentName +');">切换状态</button><button type="button" name="'+ obj.userId+
	'" class="btn btn-danger" onclick="showDeleteModule(this);">删除</button></td></tr>';
}

/**
 * 查看管理员详情
 */
function getManagementAdminDetails(target) {
	$.ajax({
		url : '../userInfo/getAdministratorInfoForPublic',
		type : 'POST',
		dataType : 'json',
		contentType : 'application/json',
		data :  JSON.stringify({
			userId : target.name
		}),
		success : function (data) {
			//console.log(data);
			if(data.success) {
				person=data.result;
				getAdminMangement(person.personName);
				setTimeout(function() {
					renderAuditContent('adminManagment');
				},150);
			}
		}
	})
}

/**
 * 打开添加平台管理员
 */
function openAddAdminModal() {
	showModal('../modalTemplates/adminReg.html');
	setTimeout(function() {
		verificationField();
	},150);
}


/**
 * 添加平台管理员
 */
function addAdmin() {
	var bootstrapValidator = $("#adminRegForm").data('bootstrapValidator');
	bootstrapValidator.validate();
    if(bootstrapValidator.isValid()){ 
    	getAdminFormField();
    	admin.userType = 6;
    	saveAdminInfo();
    }else{
    	//验证失败
    	toastr.error('有信息未填写，填写完指定信息再次提交');
    }
}
/**
 * 保存注册平台管理员的信息
 */
function saveAdminInfo() {
	$.ajax({
		url : '../user/addAdministrator',
		type : 'POST',
		dataType: "json",
		contentType : 'application/json',
		data : JSON.stringify(admin),
		success : function(result) {
			if(result.success) {
				toastr.success(result.msg);
				setTimeout(function() {
					getAdminByCondition();
					$("#modalModule").modal('hide');
				},300);
			}else{
				toastr.error(result.msg);
			}
		}
  });
}


/**
 * 获取当前表单，遍历其每个字段的值
 */
function getAdminFormField() {
	//普通文本框
	$.each($('#adminRegForm').serializeArray(), function() {
		admin[this.name] = (this.value === null ? "" : this.value);
	})
}

//验证注册字段
function verificationField(){
	$('#adminRegForm').bootstrapValidator({
		message : '值不能为空',
		//验证字段
		fields : {
			//用户账号
			userId : {
				message : '用户名验证失败',
				validators : {
					notEmpty: {
						message : '用户名不能为空'
					}
				}
			},
			//密码
			password : {
				message : '密码验证错误',
				validators : {
					notEmpty : {
						message : '密码不能为空'
					}/*,
					//验证两次密码是否相同
					identical: {
                        field: 'password2', //需要进行比较的input name值
                        message: '两次密码不一致'
                    }*/
				}
			},
			//确认密码
			password2 : {
				message : '确认密码验证错误',
				validators : {
					notEmpty : {
						message : '确认密码不能为空'
					},
					identical: {//相同
                        field: 'password',
                        message: '两次密码不一致'
                    }
				}
			},
			//邮箱格式
			email : {
				message : '邮箱验证失败',
				validators : {
					notEmpty : {
						message : '邮箱不能为空'
					},
					emailAddress : {
						message : '邮箱地址格式错误'
					}
				}
			},
			//手机验证
			phoneNumber : {
				message : '手机验证失败',
				validators :{
					notEmpty: {
                        message: '手机号码不能为空'
                    },
                    stringLength: {
                        min: 11,
                        max: 11,
                        message: '请输入11位手机号码'
                    },
                    regexp: {
                        regexp: /^1[3|5|8]{1}[0-9]{9}$/,
                        message: '请输入正确的手机号码'
                    }
				}
			}
		}
	});
}


/**
* **********************************    平台管理员模块 end    *************************
*/
/**
 * 清空表单
 */
function emptyManagementCondition() {
	var userType = auditCondition.userType;
	for(index in auditCondition) {
		auditCondition[index] = '';
	}
	var inputs = $('#findConditionTable input');
	for(var j = 0;j < inputs.length;j++) {
		$('#' + inputs[j].id).val("");
	}
	setTimeout(function() {
		getManageMentFiled(1,5,userType);
	});
}




